﻿using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Ninesky.Entities;
using Ninesky.InterfaceService;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ninesky.Models;
using System;

namespace Ninesky.WebAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/Category")]
    [EnableCors("AllowDomain")]
    public class CategoryController : Controller
    {
        private InterfaceCategoryService categoryService { get; set; }
        public CategoryController(InterfaceCategoryService interfaceCategoryService)
        {
            categoryService = interfaceCategoryService;
        }

        [HttpPost("Add")]
        public async Task<IActionResult> AddAsync([FromBody]Category category)
        {
            if (ModelState.IsValid)
            {
                //检查父栏目
                Category parentCategory = null;
                if (category.ParentId > 0)
                {
                    parentCategory = await categoryService.FindAsync(category.ParentId);
                    if (parentCategory == null) ModelState.AddModelError("ParentId", "父栏目不存在。");
                    else if (parentCategory.Type != CategoryType.General) ModelState.AddModelError("ParentId", "父栏目不是常规栏目。");
                }
                else if (category.ParentId != 0) category.ParentId = 0;
                switch (category.Type)
                {
                    //常规栏目
                    case CategoryType.General:
                        if (string.IsNullOrEmpty(category.HomeTemplate)) ModelState.AddModelError("HomeTemplate", "请输入首页模板。");
                        if (category.ContentType != ContentType.NotSet)
                        {
                            if (string.IsNullOrEmpty(category.ContentTemplate)) ModelState.AddModelError("ContentTemplate", "请输入内容页模板。");
                            if (string.IsNullOrEmpty(category.ListTemplate)) ModelState.AddModelError("ListTemplate", "请输入列表页模板。");
                        }
                        if (category.ParentId > 0)
                        {
                            category.Depth = parentCategory.Depth + 1;
                            category.ParentPath = parentCategory.ParentPath + "," + parentCategory.CategoryId;
                        }
                        else
                        {
                            category.Depth = 0;
                            category.ParentPath = "0";
                        }
                        break;
                    case CategoryType.Page:
                        if (string.IsNullOrEmpty(category.HomeTemplate)) ModelState.AddModelError("HomeTemplate", "请输入首页模板。");
                        break;
                    case CategoryType.Link:
                        if (string.IsNullOrEmpty(category.LinkUrl)) ModelState.AddModelError("LinkUrl", "请输入链接地址。");
                        break;
                    default:
                        ModelState.AddModelError("Type", "栏目类型错误。");
                        break;
                }
                if(ModelState.IsValid)
                {
                    var result = await categoryService.AddAsync(category);
                    if (result.Succeed)
                    {
                        return Ok(new { id = category.CategoryId });
                    }
                    else ModelState.AddModelError("", result.Message);
                }
            }
            return BadRequest(ModelState);
        }

        /// <summary>
        /// 修改栏目
        /// </summary>
        /// <param name="category">栏目实体</param>
        /// <returns></returns>
        [HttpPut("Modify")]
        public async Task<IActionResult> ModifyAsync([FromBody] Category category)
        {
            if (!Enum.IsDefined(typeof(CategoryType), category.Type)) ModelState.AddModelError("Type", "栏目类型错误");
            var originCategory = await categoryService.FindAsync(category.CategoryId);
            if (originCategory == null) ModelState.AddModelError("", "您修改的栏目不存在，请确定是否已删除");
            //父栏目
            Category parentCategory = null;
            if (category.ParentId > 0) {
                parentCategory = await categoryService.FindAsync(category.ParentId);
                if(parentCategory.Type != CategoryType.General) ModelState.AddModelError("ParentId", "父栏目不是常规栏目");
            }
            if(originCategory.Type == CategoryType.General && category.Type != CategoryType.General)
            {
                if(await categoryService.AnyAsync(c=>c.ParentId== originCategory.CategoryId)) ModelState.AddModelError("", "该栏目存在子栏目，不能修改栏目类型。");
            }
            if (ModelState.IsValid)
            {
                switch(category.Type)
                {
                    case CategoryType.General:
                        if(string.IsNullOrEmpty(category.HomeTemplate)) ModelState.AddModelError("HomeTemplate", "请输入栏目首页模板。");
                        if (category.ParentId == category.CategoryId) ModelState.AddModelError("ParentId", "父栏目不能是其本身");
                        if (category.ParentId > 0)
                        {
                            string[] parentIdArry = parentCategory.ParentPath.Split(new char[] { ',' });
                            if (parentIdArry.Any(id => id == category.CategoryId.ToString())) ModelState.AddModelError("ParentId", "父栏目不能是当前栏目的子栏目。");
                        }
                        if (category.ContentType != ContentType.NotSet)
                        {
                            if (string.IsNullOrEmpty(category.ContentTemplate)) ModelState.AddModelError("ContentTemplate", "请输入内容页模板。");
                            if (string.IsNullOrEmpty(category.ListTemplate)) ModelState.AddModelError("ListTemplate", "请输入列表页模板。");
                        }
                        break;
                    case CategoryType.Page:
                        if (string.IsNullOrEmpty(category.HomeTemplate)) ModelState.AddModelError("HomeTemplate", "请输入栏目首页模板。");
                        break;
                    case CategoryType.Link:
                        if (string.IsNullOrEmpty(category.LinkUrl)) ModelState.AddModelError("LinkUrl", "请输入链接地址。");
                        break;
                }
                if (ModelState.IsValid)
                {
                    if (originCategory.ContentTemplate != category.ContentTemplate) originCategory.ContentTemplate = category.ContentTemplate;
                    if (originCategory.ContentType != category.ContentType) originCategory.ContentType = category.ContentType;
                    if (originCategory.ParentId != category.ParentId)
                    {
                        if (category.ParentId > 0) originCategory.Depth = parentCategory.Depth + 1;
                        else originCategory.Depth = 1;
                    }
                    if (originCategory.Description != category.Description) originCategory.Description = category.Description;
                    if (originCategory.HomeTemplate != category.HomeTemplate) originCategory.HomeTemplate = category.HomeTemplate;
                    if (originCategory.LinkUrl != category.LinkUrl) originCategory.LinkUrl = category.LinkUrl;
                    if (originCategory.ListTemplate != category.ListTemplate) originCategory.ListTemplate = category.ListTemplate;
                    if (originCategory.Meta_Description != category.Meta_Description) originCategory.Meta_Description = category.Meta_Description;
                    if (originCategory.Meta_Keywords != category.Meta_Keywords) originCategory.Meta_Keywords = category.Meta_Keywords;
                    if (originCategory.Name != category.Name) originCategory.Name = category.Name;
                    if (originCategory.Order != category.Order) originCategory.Order = category.Order;
                    if (originCategory.ParentId != category.ParentId) originCategory.ParentId = category.ParentId;
                    if(originCategory.ParentPath != category.ParentPath)
                    {
                        if (category.ParentId > 0) originCategory.ParentPath = parentCategory.ParentPath + "," + parentCategory.CategoryId;
                        else originCategory.ParentPath = "0";
                    }
                    if (originCategory.Type != category.Type) originCategory.Type = category.Type;
                }
                var operationResult = await categoryService.UpdateAsync(originCategory);
                if (operationResult.Succeed) return Ok("修改栏目成功");
                else return BadRequest(operationResult.Message);
            }
            return BadRequest(ModelState);
        }

        /// <summary>
        /// 删除栏目
        /// </summary>
        /// <param name="id">栏目Id</param>
        /// <returns>
        /// 删除成功：返回Ok（消息）
        /// 删除失败：返回BadRequest（消息）</returns>
        [HttpDelete("Delete")]
        public async Task<IActionResult> DeleteAsync(int id)
        {
            var category = await categoryService.FindAsync(id);
            if (category == null) return BadRequest("栏目不存在，可能已被删除");
            //检查常规栏目
            if (category.Type == CategoryType.General)
            {
                //检查是否存在子栏目
                if (await categoryService.AnyAsync(c => c.ParentId == id)) return BadRequest("请先删除子栏目");
                //检查栏目是否有内容
                switch (category.ContentType)
                {
                    //文章栏目
                    case ContentType.Article:
                        //检查
                        break;
                }
            }
            var operationResult = await categoryService.DeleteAsync(category);
            if (operationResult.Succeed) return Ok(operationResult.Message);
            else return BadRequest(operationResult.Message);
        }

        /// <summary>
        /// 查找栏目
        /// </summary>
        /// <param name="id">栏目Id</param>
        /// <returns>
        /// </returns>
        [HttpGet("Find")]
        public async Task<IActionResult> GetAsync(int id)
        {
            var category = await categoryService.FindAsync(id);
            if (category == null) return BadRequest("栏目不存在");
            else
            {
                var categoryVM = new CategoryModelView(category);
                return Ok(categoryVM);
            }
        }
        /// <summary>
        /// 常规栏目
        /// </summary>
        /// <returns></returns>
        [HttpGet("General")]
        public IActionResult General()
        {
            List<CategoryControlNode> nodes = new List<CategoryControlNode>();
            var categories = categoryService.FindList(c => c.Type == CategoryType.General).OrderBy(c=>c.Order).ToList();
            var root = categories.Where(c => c.ParentId == 0).OrderBy(c=>c.Order);
            foreach (var category in root)
            {
                var node = new CategoryControlNode() { Label = category.Name, Value = category.CategoryId };
                if (categories.Any(c => c.ParentId == category.CategoryId)) node = GetGeneralRecursive(node, categories);
                nodes.Add(node);
            }
            return Ok(nodes);
        }
        /// <summary>
        /// GetGeneral递归函数
        /// </summary>
        /// <param name="node"></param>
        /// <param name="categories"></param>
        /// <returns></returns>
        public CategoryControlNode GetGeneralRecursive(CategoryControlNode node, List<Category> categories)
        {
            var children = categories.Where(c => c.ParentId == node.Value).OrderBy(c=>c.Order);
            foreach (var category in children)
            {
                var childnode = new CategoryControlNode() { Label = category.Name, Value = category.CategoryId};
                if (categories.Any(c => c.ParentId == category.CategoryId)) childnode = GetGeneralRecursive(childnode, categories);
                node.Children.Add(childnode);
            }
            return node;
        }

        [HttpGet("Tree")]
        public IActionResult Tree()
        {
            List<CategoryTreeNode> nodes = new List<CategoryTreeNode>();
            var categories = categoryService.FindList(c => true).OrderBy(c => c.Order).ToList();
            var root = categories.Where(c => c.ParentId == 0).OrderBy(c => c.Order);
            foreach (var category in root)
            {
                var node = new CategoryTreeNode { Title = category.Name, Value = category.CategoryId, Type = category.Type.ToString() };
                if (categories.Any(c => c.ParentId == category.CategoryId)) node = GetTreeRecursive(node, categories);
                nodes.Add(node);
            }
            return Ok(nodes);
        }

        /// <summary>
        /// GetTree递归函数
        /// </summary>
        /// <param name="node"></param>
        /// <param name="categories"></param>
        /// <returns></returns>
        public CategoryTreeNode GetTreeRecursive(CategoryTreeNode node, List<Category> categories)
        {
            var children = categories.Where(c => c.ParentId == node.Value).OrderBy(c => c.Order);
            foreach (var category in children)
            {
                var childnode = new CategoryTreeNode() { Title = category.Name,Value= category.CategoryId, Type = category.Type.ToString() };
                if (categories.Any(c => c.ParentId == category.CategoryId)) childnode = GetTreeRecursive(childnode, categories);
                node.Children.Add(childnode);
            }
            return node;
        }
    }
}